//
//  JDStatusCell.swift
//  JDWeiBo
//
//  Created by apple on 15/7/2.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SDWebImage

protocol StatusCellDelegate: NSObjectProtocol {
    ///  选中照片代理方法
    func statusCellDidSelectedPhoto(cell: JDStatusCell, photoIndex: Int)
}

/// 转发微博 cell
let JDStatusForwardCellIdentifier = "JDStatusForwardCellIdentifier"
/// 原创微博 cell
let JDStatusNormalCellIdentifier = "JDStatusNormalCellIdentifier"
/// 图片可重用的标记
private let JDPictureCellReuseIdentifier = "JDPictureCellReuseIdentifier"

class JDStatusCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {

    /// 照片代理 - 提示，不要用 delegate
    weak var photoDelegate: StatusCellDelegate?
    
    // 提取视图约束的宽
    var widthCons : NSLayoutConstraint?
    // 提取视图约束的高
    var heighCons : NSLayoutConstraint?
    /// 配图视图顶部约束
    private var topCons: NSLayoutConstraint?
    
    /// 转发微博标签
    var forwardLabel: UILabel?
    
    ///  微博数据模型
    var status: JDStatus? {
        didSet {
            
            // 转发文字
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")
            
            // 设置头像
            iconView.sd_setImageWithURL(status?.user?.profileURL)
            // 设置认证图标
            vipIconView.image = status?.user?.verifiedImage
            // 设置会员图片
            memberIconView.image = status?.user?.mbImage
            
            nameLabel.text = status?.user?.name
            timeLabel.text = "刚刚"
            sourceLabel.text = "来自 微博"
            contentLabel.text = status?.text
            
            // 计算图片视图的大小
//            print("\(status?.imageURLs?.count) \(calcPictureViewSize(status!))")
            let result = calcPictureViewSize(status!)
            // 设置配图视图约束大小
            topCons?.constant = result.viewSize.height == 0 ? 0 : 12 // 没有图片，需要处理顶部约束
            widthCons?.constant = result.viewSize.width
            heighCons?.constant = result.viewSize.height
            pictureLayout.itemSize = result.itemSize
            
            // 刷新图片视图
            pictureView.reloadData()
        }
    }
    
    /// cell 的可重用 标示符
    class func cellIdentifier(status: JDStatus) -> String {
//        return JDStatusNormalCellIdentifier
        return status.retweeted_status != nil ? JDStatusForwardCellIdentifier : JDStatusNormalCellIdentifier
    }
    
    ///  计算行高
    func rowHeight(status: JDStatus) -> CGFloat {
        // 给模型设置数值，调用 didSet 方法
        self.status = status
        
        // 更新布局
        layoutIfNeeded()
        
        // 返回行高 - 页脚视图的底边
        return CGRectGetMaxY(footerView.frame)
    }
    
    // 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        print("==============\(status?.picURLs?.count)")
        return status?.picURLs!.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(JDPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        
        // 调用此数据源方法，说明上面的数据行数有效，证明数组一定有内容
        cell.imageURL = status!.picURLs![indexPath.item]
//        if status?.retweeted_status != nil {
//            print(status?.picURLs?.count)
//        }
        
        return cell
    }
    
    // 更具模型计算大小
    private func calcPictureViewSize(status: JDStatus) -> (viewSize: CGSize, itemSize: CGSize) {
        
        // 0. 获取图片数量
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        
        let count = status.imageURLs?.count ?? 0
        
        // 1. 没有图片
        if count == 0 {
            return (CGSizeZero, itemSize)
        }
        
        // 2. 单图
        if count == 1 {
            let key = status.picURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
//            print("单张图片 \(key) \(image.size)")
            
            // 返回 image.size
            return (image.size, image.size)
        }
        
        // 多张图片
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w), itemSize)
        }
        
        // 多张图片
        // 每行图片数量
        let rowCount = 3
        // 计算行数
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        
        return (CGSize(width: w, height: h), itemSize)
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        // 屏幕宽度
        let screenWidth = UIScreen.mainScreen().bounds.width
        
        // 顶部视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.5, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWidth, height: 10))
        
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 16
        addSubview(pictureView)
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        // 准备配图视图
        preparePictureView()
    
        /**
        ///  对齐类型枚举，设置控件相对于父视图的位置
        ///
        ///  - TopLeft:      左上
        ///  - TopRight:     右上
        ///  - TopCenter:    中上
        ///  - BottomLeft:   左下
        ///  - BottomRight:  右下
        ///  - BottomCenter: 中下
        ///  - CenterLeft:   左中
        ///  - CenterRight:  右中
        ///  - CenterCenter: 中中
        */
        
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 12))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))
        // TODO
        // 页脚视图
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44), offset: CGPoint(x: -12, y: 12))
    }

        required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///  选中照片代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 照片索引只需要传递 `Int` 会简化调用方的使用
        photoDelegate?.statusCellDidSelectedPhoto(self, photoIndex: indexPath.item)
    }
    
    ///  记录配图视图约束
    func recordPictureViewCons(cons: [NSLayoutConstraint]) {
        topCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heighCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    
    
    ///  准备配图视图图
    private func preparePictureView() {
        // 设置背景颜色
        pictureView.backgroundColor = UIColor.clearColor()
        // 数据源
        pictureView.dataSource = self
        
        pictureView.delegate = self
        
        // 注册可重用cell
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: JDPictureCellReuseIdentifier)
        // 设置 layout
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
    }
    
    ///  懒加载
    lazy var iconView = UIImageView()
    
    lazy var nameLabel : UILabel = {
        
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.darkGrayColor()
        return label
    }()
    
    lazy var memberIconView : UIImageView = UIImageView(image: UIImage(named:"common_icon_membership_level1"))
    
    lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    
    lazy var timeLabel:UILabel  = {
        
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(10)
        label.textColor = UIColor.orangeColor()
        
        return label
        }()
    
    lazy var sourceLabel:UILabel  = {
        
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(10)
        label.textColor = UIColor.darkGrayColor()
        
        return label
        }()
    
    lazy var contentLabel:UILabel = {
        
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(15)
        label.textColor = UIColor.darkGrayColor()
        label.numberOfLines = 0
        
        return label
        }()
    
    // 视图
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
    // 页脚视图
     //lazy var footerView: JDStatusForwardCell = JDStatusForwardCell()
    lazy var footerView : StatusFooterView = StatusFooterView()
    
    
}

// 配图Cell

private class StatusPictureCell : UICollectionViewCell {
    
    /// 图像地址
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL)
            
            // 根据 url 的扩展名，判断是否设置 gif / GIF
            gifIconView.hidden = !(imageURL!.absoluteString.pathExtension.lowercaseString == "gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 设置图片填充模式
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        // 配合使用
        iconView.clipsToBounds = true
        
        addSubview(iconView)
        // 与 collectionView 完全一致
        iconView.ff_Fill(self)
        
        addSubview(gifIconView)
        gifIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil)
    }
    
    private lazy var gifIconView: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "timeline_image_gif"))
        iv.hidden = true
        
        return iv
        }()
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var iconView = UIImageView()
    
}

/// 页脚视图
class StatusFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        // 布局，水平平铺
        ff_HorizontalTile([forwardBtn, commentBtn, likeBtn], insets: UIEdgeInsetsZero)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn: UIButton = {
        let btn = UIButton()
        
        btn.setTitle("转发", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_retweet"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
        }()
    
    lazy var commentBtn: UIButton = {
        let btn = UIButton()
        
        btn.setTitle("评论", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_comment"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
        }()
    
    lazy var likeBtn: UIButton = {
        let btn = UIButton()
        
        btn.setTitle("点赞", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_unlike"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
        }()
}